package cn.virens.common.boot.dubbo.consumer.beetl.format;

import cn.virens.common.util.exception.APIException;
import com.alibaba.fastjson2.JSON;
import org.beetl.core.Format;
import org.dromara.hutool.core.codec.binary.Base64;

public class JSONFormat implements Format {

    @Override
    public Object format(Object data, String pattern) throws APIException {
        if (pattern != null && "base64".equals(pattern)) {
            return Base64.encode(toString(data));
        } else {
            return toString(data);
        }
    }

    private static String toString(Object data) throws APIException {
        return data != null ? JSON.toJSONString(data) : "{}";
    }
}
